#!/bin/sh
#
# Usage:
#   ./5-tools.sh <function name>

. $PWD/util.sh

do_ncurses() {
  maybe_untar_cd ncurses-5.9 .tar.gz

  set -o errexit
  ./configure --prefix=/tools --with-shared \
        --without-debug --without-ada --enable-overwrite

  make
  make install
}

_patch_bash() {
  patch -Np1 -i ../bash-4.2-fixes-12.patch
}

# NOTE: First time around, host machine may require yacc to build bash.

do_bash() {
  maybe_untar_cd bash-4.2 .tar.gz

  set -o errexit
  _patch_bash

  ./configure --prefix=/tools --without-bash-malloc

  make
  make install

  ln -sv bash /tools/bin/sh
}

do_bzip2() {
  maybe_untar_cd bzip2-1.0.6 .tar.gz

  set -o errexit

  # no configure!
  make
  make PREFIX=/tools install
}

do_coreutils() {
  maybe_untar_cd coreutils-8.21 .tar.xz

  set -o errexit
  ./configure --prefix=/tools --enable-install-program=hostname
  make
  make install
}

do_diffutils() {
  conf_build_install diffutils-3.3 .tar.xz
}

do_file() {
  conf_build_install file-5.14 .tar.gz
}

do_findutils() {
  conf_build_install findutils-4.4.2 .tar.gz
}

do_gawk() {
  conf_build_install gawk-4.1.0 .tar.xz
}

do_gettext() {
  maybe_untar_cd gettext-0.18.3 .tar.gz

  set -o errexit

  # Just build one program
  cd gettext-tools
  EMACS="no" ./configure --prefix=/tools --disable-shared

  make -C gnulib-lib
  make -C src msgfmt

  cp -v src/msgfmt /tools/bin
}

do_grep() {
  conf_build_install grep-2.14 .tar.xz
}

do_gzip() {
  conf_build_install gzip-1.6 .tar.xz
}

do_m4() {
  maybe_untar_cd m4-1.4.16 .tar.bz2

  set -o errexit

  # patch
  sed -i -e '/gets is a/d' lib/stdio.in.h

  ./configure --prefix=/tools
  make
  make install
}

do_make() {
  conf_build_install make-3.82 .tar.bz2
}

do_patch() {
  conf_build_install patch-2.7.1 .tar.xz
}

do_perl() {
  maybe_untar_cd perl-5.18.1 .tar.bz2

  set -o errexit

  patch -Np1 -i ../perl-5.18.1-libc-1.patch

  sh Configure -des -Dprefix=/tools
  make

  # install
  cp -v perl cpan/podlators/pod2man /tools/bin
  mkdir -pv /tools/lib/perl5/5.18.1
  cp -Rv lib/* /tools/lib/perl5/5.18.1
}

do_sed() {
  conf_build_install sed-4.2.2 .tar.bz2
}

do_tar() {
  maybe_untar_cd tar-1.26 .tar.bz2

  set -o errexit

  # patch
  sed -i -e '/gets is a/d' gnu/stdio.in.h

  ./configure --prefix=/tools
  make
  make install
}

do_texinfo() {
  conf_build_install texinfo-5.1 .tar.xz
}

do_xz() {
  conf_build_install xz-5.0.5 .tar.xz
}

"$@"
